<template>
  <div class="basicForm">
    <editForm :formConfig="basicConfig" ref="basicForm" :formData="formData">
      <template #planCode="{ editFormInfo }">
        <el-input
          v-model="editFormInfo.planCode"
          size="mini"
          class="input-with-select input-link"
          readonly
          :disabled="true"
          placeholder="请选择工单"
          @click.native="showPlanPackage(editFormInfo)"
        ></el-input>
      </template>
    </editForm>
    <div class="attachConten">
      <div class="attachTitle">附件:</div>
      <div class="tebleDiv">
        <attachFormNew
          style="width: 60%"
          :disabled="baseAttachBtn"
          :attachSetting="attachSetting"
          isDelete
          multiple
          ref="attachForm"
        ></attachFormNew>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getDetailsApi, //获取大修工单详情
  getWorkListFormApi, //获取大修的作业表单
} from "@/api/orderManagement/overhaul";
import {
  getPresetParamsApi, //获取设备参数
} from "@/api/common";
export default {
  props: {
    initData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    pageType: {
      type: String,
      default: "",
    },
    oldMajor:{
      type: String,
      default: null
    }
  },
  components: {},
  data() {
    return {
      formData: {},
      orderTitle: "",
      status: "",
      workplace: [],
      currentEquipmentName: "",
      equipmentDeptName: "",
      basicConfig: {
        itemArr: [
          {
            label: "设备名称",
            prop: "equipmentName", //多选时，字段要为数组类型
            propArr: "equipmentArr",
            idsStr: "equipmentId",
            filterConfig: ["hasManagerUnit", "filterStandard"],
            //过滤条件：hasManagerUnit:该设备是否关联单位，filterManagerUnit:筛选指定单位的设备,filterStandard:关联了标准的设备
            managerUnit: [], //指定过滤的设备管理单位id filterConfig包含filterManagerUnit的时候使用
            standardType: "overhaul",
            //标准类型 正常维护：maintain,大修：overhaul,检修：repair,试验：experiment，巡视：patrol
            multiple: false, //是否多选
            allowCreate: false, //是否允许创建条目
            option: [], //this.deptOption
            type: "device-select", //类型
            trigger: "change",
            required: true,
            methods: (obj) => {
              this.currentDevice = obj[0] || {};
              if (JSON.stringify(this.currentDevice) == "{}") {
                this.equipmentDeptName = "";
                this.$refs.basicForm.setFormItem("deptManageName", "");
                this.$refs.basicForm.setFormItem("deptManage", "");
                this.$refs.basicForm.setFormItem("major", "");
                this.$emit("setWorkListData", []);
              } else {
                let { name, id, typeId } = obj[0];
                this.currentEquipmentName = name;
                let factTypeId = typeId||this.formData.typeId;
                let form = { equipmentId: id, factTypeId };
                this.$refs.basicForm.setFormItem("typeId", factTypeId);
                this.setDeptManage(form);
                this.getWorkListForm(factTypeId);
              }
            },
            rows: 2,
            span: 6,
          },
          {
            label: "设备管理单位",
            prop: "deptManageName",
            idsStr: "deptManage",
            type: "text",
            disabled: true,
            required: true,
            span: 6,
          },
          {
            type: "select",
            label: "专业",
            prop: "major",
            required: true,
            selectOption: this.$store.getters["dirtData"]("common_major"),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "common_major",
                val
              );
            },
            span: 6,
          },
          {
            type: "select",
            label: "工单来源",
            prop: "source",
            selectOption: this.$store.getters["dirtData"]("order_source"),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "order_source",
                val
              );
            },
            methods: (obj) => {},
            // required: true,
            disabled: true,
            span: 6,
          },
          {
            label: "计划编号",
            prop: "planCode",
            type: "text",
            isHide: true,
            disabled: false,
            min: 0,
            span: 6,
          },
          {
            label: "主办单位",
            prop: "deptWorkName", //多选时，字段要为数组类型
            propArr: "deptWorkArr",
            idsStr: "deptWork",
            multiple: false, //是否多选
            isOutOrg: 0, //是否是外单位
            option: [], //this.deptOption1
            allowCreate: true, //是否允许创建条目
            type: "dept-select", //类型
            trigger: "change",
            methods: (obj) => {},
            required: true,
            span: 6,
          },
          // {
          //   label: "工作地点",
          //   prop: "locationName",
          //   idsStr: "location",
          //   type: "location",
          //   trigger: "change",
          //   required: true,
          //   methods: obj => {},
          //   span: 6
          // },

          {
            label: "工作地点",
            prop: "locationName", //多选时，字段要为数组类型
            propArr: "locationArr",
            idsStr: "location",
            orgStr: "locationType", //
            multiple: true, //是否多选
            option: [], //this.deptOption1
            allowCreate: true, //是否允许创建条目
            type: "location-select", //类型
            trigger: "change",
            methods: (obj) => {
              this.workplace = [];
              obj.map((i) => {
                let place = {
                  location: i.isOutOrg == "-1" ? "" : i.value,
                  locationName: i.label,
                  orderId: this.formData.id,
                  orderType: "overhaul",
                };
                this.workplace.push(place);
              });
            },
            required: true,
            rows: 1,
            span: 6,
          },
          {
            label: "计划起止时间",
            prop: "dispatchTime",
            type: "datetimerange",
            required: true,
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() < Date.now() - 3600 * 1000 * 24;
              },
            },
            methods: (obj) => {
              let startTime = new Date(obj[0]);
              let endTime = new Date(obj[1]);
              let timeLimit = (endTime - startTime) / 1000 / 60 / 60 / 24;
              this.$refs.basicForm.setFormItem(
                "timeLimit",
                timeLimit.toFixed(2)
              );
            },
            span: 6,
          },
          {
            label: "工期(天)",
            prop: "timeLimit",
            placeholder: "选完起止时间后自动计算",
            type: "text",
            required: true,
            disabled: true,
            span: 6,
          },
          {
            type: "select",
            label: "工单性质",
            prop: "nature",
            required: true,
            selectOption: [
              {
                name: "生产类",
                label: "生产类",
                value: true,
              },
              {
                name: "非生产类",
                label: "非生产类",
                value: false,
              },
            ],
            span: 6,
          },
          {
            type: "select",
            label: "检修等级",
            prop: "repairLevel",
            selectOption: this.$store.getters["dirtData"]("overhaul_repair_level"),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "overhaul_repair_level",
                val
              );
            },
            methods: (obj) => {},
            required: true,
            disabled: false,
            span: 6,
          },
          {
            type: "select",
            label: "检修类型",
            prop: "repairType",
            selectOption: this.$store.getters["dirtData"]("overhaul_repair_type"),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "overhaul_repair_type",
                val
              );
            },
            methods: (obj) => {},
            required: true,
            disabled: false,
            span: 6,
          },
          {
            label: "施工单位",
            prop: "buildUnit", //多选时，字段要为数组类型
            // propArr: "buildUnitArr",
            // idsStr: "buildUnit",
            // multiple: false, //是否多选
            // isOutOrg: 0, //是否是外单位
            // option: [], //this.deptOption1
            // allowCreate: true, //是否允许创建条目
            type: "text", //类型
            trigger: "change",
            methods: (obj) => {},
            required: false,
            span: 6,
          },
          {
            /* 缺陷工单 */
            label: "占位",
            prop: "placeholder",
            otherInfo: "table",
            isChange: false,
            span: 18,
          },
          {
            label: "工作内容",
            prop: "context",
            type: "textarea",
            maxlength: "100",
            required: true,
            methods: (obj) => {},
            span: 12,
            rows: 4,
          },
          {
            label: "备注",
            prop: "marks",
            type: "textarea",
            maxlength: "100",
            span: 12,
            rows: 4,
          },
        ],
      },
      //附件设置
      attachSetting: {
        businessId: "", //单据的ID
        businessType: "base",
      },
      option: {
        1: "Ⅰ",
        2: "Ⅱ",
        3: "Ⅲ",
      },
    };
  },
  computed: {
    baseAttachBtn() {
      let status = this.formData.status || "";
      if (["DRAFT", ""].includes(status) && this.pageType != "detail") {
        return false;
      } else {
        return true;
      }
    },
    defaultTitle() {
      return this.equipmentDeptName + this.currentEquipmentName + "大修";
    },
  },
  watch: {
    defaultTitle: {
      handler(val) {
        this.orderTitle = val;
        this.$emit("setOrderTitle", val);
      },
    },
    pageType: {
      handler(val) {
        if (val != "add") {
          this.initForm();
          let majors = this.formData.majors || [];
          let status = this.formData.status || null;
          if (majors.length > 0) {
            majors.map((i, index) => {
              i.collapseActive = ""; //初始化collapse
              i.index = index;
              i.forms.map((j, index) => {
                j.index = index;
                j.overhaulReadies.map((k) => {
                  if (
                    ["DRAFT", "IN_EXECUTE"].includes(status) &&
                    ["edit", "add"].includes(val)
                  ) {
                    k.editable = true;
                  } else {
                    k.editable = false;
                  }
                });
                this.initTableData(j.itemDTOs, j.stepLevel);
              });
            });
          }
          this.$emit("changeFormData", this.formData);
        } else {
          this.init();
        }
      },
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.formData = this.initData;
      if (this.pageType == "add") {
        this.formData.sourceId = "enter_order";
        this.formData.source = "手工录入";
      }
    },
    initForm() {
      let itemArr = [];
      $.extend(true, itemArr, this.basicConfig.itemArr);
      itemArr.map((i) => {
        if (
          this.status != "DRAFT" ||
          ["query", "detail"].includes(this.pageType)
        ) {
          i.disabled = true;
        } else {
          if (!["source", "deptManageName", "timeLimit"].includes(i.prop)) {
            i.disabled = false;
          } else {
            i.disabled = true;
          }
        }
      });

      this.basicConfig.itemArr = itemArr;
    },

    //获取大修工单基本信息
    getDetails(id) {
      let dataId = id ? id : this.formData.id;
      getDetailsApi(dataId).then((res) => {
        let data = res.data || {};
        if (this.oldMajor) {
          data.major = this.oldMajor;
        }
        this.status = data.status;
        this.initForm();
        if (JSON.stringify(data) != "{}") {
          this.currentEquipmentName = data.equipmentName;
          this.equipmentDeptName = data.deptManageName;
          this.orderTitle = data.title;
          this.workplace = data.orderLocationList;
          if (data.planCode) {
            this.basicConfig.itemArr[4].isHide = false;
          }
          this.$emit("setOrderTitle", data.title);
          if (
            data.title == data.deptManageName + data.equipmentName + "大修" ||
            [null, ""].includes(data.title)
          ) {
            //用户是否自定义了工单名
            if ([null, ""].includes(data.title)) {
              this.$message.warning("检测到工单标题为空，已为您自动生成标题！");
              this.orderTitle =
                data.deptManageName + data.equipmentName + "大修";
              this.$emit("setOrderTitle", this.orderTitle);
            }
            this.$emit("initUserInput", false);
          } else {
            this.$emit("initUserInput", true);
          }

          /* 工期 */
          data.timeLimit = this.$utils.getTimeDiffe(
            new Date(data.startTime),
            new Date(data.endTime)
          );
          this.status = data.status;
          //判断作业过程表格里面的数据是否还有下一层级
          if (data.majors.length == 0 && data.sourceId == "plan_order") {
            this.basicConfig.itemArr.map((i) => {
              if (["locationName", "nature","repairLevel","repairType","buildUnit"].includes(i.prop)) {
                i.disabled = false;
              } else {
                i.disabled = true;
              }
            });
            //计划生成的大修工单，刚开始没有作业表单
            this.getWorkListForm(data.typeId);
          } else {
            data.majors.map((i, index) => {
              i.collapseActive = ""; //初始化collapse
              i.index = index;
              i.forms.map((j, index) => {
                j.index = index;
                j.overhaulReadies.map((k) => {
                  if (
                    data.status == "DRAFT" &&
                    ["edit", "add"].includes(this.pageType)
                  ) {
                    k.editable = true;
                  } else {
                    k.editable = false;
                  }
                });
                this.initTableData(j.itemDTOs, j.stepLevel);
              });
            });
          }

          this.$emit("setWorkListData", data.majors); //作业表单
          this.status = this.formData.status;
          //初始化附件ID
          this.attachSetting.businessId = data.id;
          /* 起止时间 */
          if (data.startTime) {
            data.dispatchTime = [data.startTime, data.endTime];
          }
          setTimeout(() => {
            let workplace = data.orderLocationList; //工作地点
            let placeName = [],
              placeId = [],
              placeType = [];
            workplace.map((i) => {
              placeName.push(i.locationName);
              if (i.location) {
                placeId.push(i.location);
                placeType.push("0");
              } else {
                //临时单位
                placeId.push(i.locationName);
                placeType.push("-1");
              }
            });
            data.locationName = placeName.toString();
            data.locationArr = placeId;
            data.location = placeId.toString();
            data.locationType = placeType.toString();
            let workplaceOption = this.$utils.getOptionData(
              placeName.toString(),
              placeId.toString(),
              placeType.toString()
            );

            /* 初始化主办单位 */
            let { deptWorkName, deptWork, equipmentName, equipmentId } = data;
            let deptWorkOption = this.$utils.getOptionData(
              deptWorkName,
              deptWork,
              "0"
            );
            let equipmentOption = this.$utils.getOptionData(
              equipmentName,
              equipmentId
            );
            if (this.$refs.basicForm) {
              this.$refs.basicForm.setItemOption(
                "deptWorkName",
                deptWorkOption
              );
              this.$refs.basicForm.setItemOption(
                "equipmentName",
                equipmentOption
              );
              this.$refs.basicForm.setItemOption(
                "locationName",
                workplaceOption
              );
            }
            data.deptWorkArr = deptWork;
            data.equipmentArr = equipmentId;
            this.formData = data;
          }, 100);
        }
        this.$emit("changeFormData", data);
      });
    },
    //处理作业项目的表格数据
    initTableData(data, stepLevel) {
      data.map((item, i) => {
        item.sort = i + 1;
        item.ids = item.id;
        if (this.pageType == "add") {
          delete item.id;
        }
        if (
          [null, "DRAFT", "IN_EXECUTE"].includes(this.status) &&
          ["edit", "add"].includes(this.pageType)
        ) {
          item.editable = true;
        } else {
          item.editable = false;
        }
        item.rowIndex = i;
        item.levelabel = this.option[item.level];
        item.itemParamString = this.customsHandleConfirm(item.itemParams);
        let signs = item.signs || [];
        let signName = [];
        if (signs.length) {
          signs.map((k) => {
            signName.push(k.signerName);
          });
          item.signerName = signName.toString();
        }
        let childrenArr = item.children || [];
        item.children = item.children || [];
        delete item.createTime;
        if (childrenArr.length != 0) {
          childrenArr.forEach((child, index) => {
            if (
              [null, "DRAFT", "IN_EXECUTE"].includes(this.status) &&
              ["edit", "add"].includes(this.pageType)
            ) {
              child.editable = true;
            } else {
              child.editable = false;
            }
            let downSigns = child.signs || [];
            if (downSigns.length > 0) {
              let name = [];
              downSigns.map((i) => {
                name.push(i.signerName);
              });
              child.signerName = name.toString();
            }
            child.parentIndex = i;
            child.rowIndex = index;
            child.sort = `${i + 1}.${index + 1}`;
            child.ids = child.id;
            if (this.pageType == "add") {
              delete child.id;
            }
            child.levelabel = this.option[child.level];
            child.itemParamString = this.customsHandleConfirm(child.itemParams);
            delete child.createTime;
          });
        }
      });
    },
    //通过逗号把几个输入框的值拼接起来
    customsHandleConfirm(list) {
      let string = "";
      list.forEach((item, i) => {
        delete item.createTime;
        if (i == 0) {
          string += `${item.name}(${item.unit})`;
        } else {
          string += `,${item.name}(${item.unit})`;
        }
        if (
          [null, "DRAFT", "IN_EXECUTE"].includes(this.status) &&
          ["edit", "add"].includes(this.pageType)
        ) {
          //控制数据记录项是否可编辑
          item.disabled = false;
        } else {
          item.disabled = true;
        }
      });
      //通过逗号把几个输入框的值拼接起来
      return string;
    },
    //获取作业表单数据
    getWorkListForm(typeId) {
      let form = {
        status: "1",
        typeId,
      };
      getWorkListFormApi(form).then((res) => {
        let data = res.data || [];
        if (data.length > 0) {
          data.map((i, index) => {
            i.collapseActive = ""; //初始化collapse
            i.index = index;
            i.forms.map((j, index) => {
              if (this.pageType == "add") {
                j.ids = j.id;
                delete j.id;
              }
              j.index = index;
              delete j.createBy;
              delete j.createByName;
              delete j.createTime;
              delete j.updateBy;
              delete j.updateByName;
              delete j.updateTime;
              j.overhaulReadies.map((k) => {
                if (this.pageType == "add") {
                  delete k.id;
                }
                k.editable = true;
                delete k.createTime;
              });
              this.initTableData(j.itemDTOs, j.stepLevel);
            });
          });
        }
        this.$emit("setWorkListData", data);
      });
    },
    //获取设备的设备管理单位
    async setDeptManage(form) {
      let res = await getPresetParamsApi(form);
      let deptObj = res.data["0005000"] || {};
      let majorObj = res.data["0008000"] || {};
      if (JSON.stringify(deptObj) == "{}") {
        this.$message.warning(
          "该设备没有设备管理单位，请选择有设备管理单位的设备！"
        );
        this.equipmentDeptName = "";
        this.$refs.basicForm.setFormItem("deptManageName", "");
        this.$refs.basicForm.setFormItem("deptManage", "");
      } else {
        let { paramResult, paramValue } = deptObj;
        this.equipmentDeptName = paramValue;
        this.$refs.basicForm.setFormItem("deptManageName", paramValue);
        this.$refs.basicForm.setFormItem("deptManage", paramResult);
      }
      if (!(JSON.stringify(majorObj) == "{}")) {
        let { paramResult } = majorObj;
        this.$refs.basicForm.setFormItem("major", paramResult);
      } else {
        this.$refs.basicForm.setFormItem("major", "");
      }
    },
    getFormData(isCheck) {
      return this.$refs.basicForm.getFormData(isCheck);
    },
    //返回工作地点
    getLocationList() {
      return this.workplace;
    },
    //展示大修计划
    showPlanPackage(row) {
      this.goDetailPage(row.planId, "bigChangePlanDetail", "detail");
    },
    //跳转到详情页
    goDetailPage(id, router, type) {
      const { href } = this.$router.resolve({
        name: router,
        query: {
          id: id ? id : "",
          pageType: type ? type : "",
        },
      });
      window.open(href, "_blank");
    },
    getTitle() {
      return this.orderTitle;
    },
    //保存附件
    saveAttachFile() {
      this.$refs.attachForm.save();
    },
    setAttachId(id,type) {
      new Promise((resolve, reject) => {
        this.attachSetting.businessId = id;
        resolve(this.attachSetting);
      }).then(() => {
        this.$refs.attachForm.doSubmitFiles(type);
      });
    },
  },
};
</script>
<style lang="less" scoped>
.attachConten {
  display: flex;
  flex-flow: wrap nowrap;
  .redPoint {
    color: red;
  }
  .attachTitle {
    width: 120px;
  }
  .tebleDiv {
    width: 100%;
  }
}
.input-link /deep/.el-input__inner {
  cursor: pointer;
  color: royalblue;
}
</style>
